// Web Animation API
// IntersectionObserver API
// dom -> animation
const DISTANCE = 100
const DURATION = 500
const map = new WeakMap()
const ob = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      const el = entry.target as HTMLElement
      const animation = map.get(el)
      if (animation) {
        animation.play()
      }
      ob.unobserve(el)
    }
  }
})
const isBelowViewport = (el: HTMLElement) => {
  const rect = el.getBoundingClientRect()
  return rect.top > window.innerHeight
}
export default {
  name: 'v-smooth-in',
  mounted(el: HTMLElement) {
    if (!isBelowViewport(el)) return
    const animation = el.animate(
      [
        {
          transform: `translateY(${DISTANCE}px)`,
          opacity: 0.5,
        },
        {
          transform: `translateY(0)`,
          opacity: 1,
        },
      ],
      {
        duration: DURATION,
        easing: 'ease-out',
      },
    )
    animation.pause()
    ob.observe(el)
    map.set(el, animation)
  },

  unmounted(el: HTMLElement) {
    ob.unobserve(el)
  },
}
